﻿/**
 * @author cf
 * 
 * js中常用方法
 * 
 */



/*
 * 请求接口不加密 url：地址 queDate：参数 func：回调函数 专用
 */
function doPost(url, queDate, func,errfunc) {
    var urDate = window.serverUrl+url;
    //console.log("请求地址：" + urDate + "请求数据：" + queDate);


    console.log("请求参数：" + JSON.stringify(queDate));
    $.ajax({
        type: "POST",
        url: urDate,
        timeout: window.timeout,
        // 设置超时
        data: queDate,
        dataType: "json",
        success: function(data) {
           //console.log("返回信息OK：" + JSON.stringify(data));
            if(!isNull(data)){
                //toast(JSON.stringify(data));
                 if (data.success) {
            
                    console.log("response success:" + JSON.stringify(data));
                
                    func(data);
                } else {
                    console.log("response FALSE:" + JSON.stringify(data));
                    console.log(data.errMsg);
                    // console.log(data);
                    errfunc(data);
                    
                }
            }else{
               console.log("数据解析异常");
            }
           
        },
        error: function(data) {
            console.log("返回信息错误：" + data + "\t," + JSON.stringify(data))
        }
    });
}

//退出
$(function() {
    $("#logout").click(function() {
    	doPost("login/logout.web", null, function(data) {
    		if (null != data) {
    			window.location.href =window.serverUrl+ "/html/sbbb/index.html";
    		}
    	}, function(data) {
    		alert(data.errMsg);
    	});
    });
});

/**
 * 填补请求参数
 * 
 * @param {[key]}
 * @param {value}
 */
function toJson(key, value) {
    var str = "";
    str += key + ":" + value;
    return str;
}
/* 补位 */
function PrefixInteger(num, n) {
    if(num>12){
        num=num-12;
    }
    if ((num + "").length >= n) return num;
    return PrefixInteger("0" + num, n);
}
/**
 * 判断非空
 * 
 * @param {[type]}
 *            content [内容]
 * @return {Boolean} [false 为空true非空]
 */
function isNull(content) {
    if ("" == content || typeof(content) == content || null == content || "null" == content || "," == content || "undefined" == content) {
        return true;
    } else {
        return false;
    }
}
/**
 * [isPhone 验证是否是手机号码]
 * @param  {[type]} obj [手机号码]
 * @return {[type]}     [description]
 */
function isPhone(obj) {
    var strPhone = obj;
    var phoneRegWithArea1 = /(1[1-9]\d{9}$)/;
    if (strPhone.length != 0) {
        if (phoneRegWithArea1.test(strPhone)) {
            return true;
        } else {
            return false;
        }
    }
}
/**
 * 
 * @param time
 * @returns yyyy-mm
 */
function formatDate(time) {
    if (time == null||time == "") {
        return "";
    }
    var now = new Date(time);
    var year = now.getFullYear();
    var month = now.getMonth() + 1+ "";
    if (month.length == 1) {
        month = "0" + month;
    }
    var date = now.getDate() + "";
    if (date.length == 1) {
        date = "0" + date;
    }
    return year + month;
}

/**
 * 
 * @param time
 * @param date,datetime
 * @returns yyyy-mm-dd, yyyy-mm-dd hh:mm;ss
 */
function formatDateTime(time,type) {
    if (time == null||time == "") {
        return "";
    }
    var now = new Date(time);
    var year = now.getFullYear();
    var month = now.getMonth() + 1+ "";
    var date = now.getDate() + "";
    var hh=now.getHours()+"";
    var min=now.getMinutes()+"";
    var sed=now.getSeconds()+"";
    if (month.length == 1) {
        month = "0" + month;
    }
    if (date.length == 1) {
        date = "0" + date;
    }
    if (hh.length == 1) {
        hh = "0" + hh;
    }
    if (min.length == 1) {
        min = "0" + min;
    }
    if (sed.length == 1) {
        sed = "0" + sed;
    }
    if(type=='date'){
        return year +"-"+ month+"-"+date;
    }else if(type=='datetime'){
        return year +"-"+ month+"-"+date+" "+hh+":"+min+":"+sed;
    }else if(type=='month'){
    	return year +"-"+ month;
    }else if(type=='minute'){
        return year +"-"+ month+"-"+date+" "+hh+":"+min;
    }

}
/**
 * 获取url里面的传值
 * 
 * @param name
 * @returns {null}
 */
function getUrlParam(name) {
    // 构造一个含有目标参数的正则表达式对象
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    // 匹配目标参数
    var r = window.location.search.substr(1).match(reg);
    // 返回参数值
    if (r != null) return unescape(r[2]);
    return null;
}

function getParentUrlParam(name) {
    // 构造一个含有目标参数的正则表达式对象
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    // 匹配目标参数
    var r = window.parent.document.URL.search.substr(1).match(reg);
    // 返回参数值
    if (r != null) return unescape(r[2]);
    return null;
}

// 计算月份差格式 200303 - 200305
 function getMonthNumber(date1,date2){
    // 默认格式为"20030303",根据自己需要改格式和方法
    var year1 =  date1.substr(0,4);
    var year2 =  date2.substr(0,4); 
    var month1 = date1.substr(4,2);
    var month2 = date2.substr(4,2);
    var len=(year2-year1)*12+(month2-month1)+1;
    return len;
 }


/**
 * 将参数转换成对象
 */
function parseQueryString(url) {
    var reg_url = /^[^\?]+\?([\w\W]+)$/,
    reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g,
    arr_url = reg_url.exec(url),
    ret = {};
    if (arr_url && arr_url[1]) {
        var str_para = arr_url[1], result;
        while ((result = reg_para.exec(str_para)) != null) {
            ret[result[1]] = result[2];
        }
    }
    return ret;
}


/**
 * 判断是否正确手机号
 * 
 * @param phone
 * @returns {boolean}
 */
function vailPhone(phone){
    var flag = false;
    var message = "";
    var myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(17[0-9]{1})|(15[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
    if(phone == ''){
        message = "手机号码不能为空！";
    }else if(phone.length !=11){
        message = "请输入有效的手机号码！";
    }else if(!myreg.test(phone)){
        message = "请输入有效的手机号码！";
    }else{
        flag = true;
    }
    if(!flag){
        // 提示错误效果
    }else{
        // 提示正确效果

    }
    return flag;
}

/**
 * 初始化表单数据
 */
function initFormData(jqSelector, data) {
	var form = $(jqSelector);
	var nameTimes = {};
	form.find(":input").each(function(index,input){
		var _this = $(this);
		var _this_name = _this.attr("name");
		
		nameTimes[_this_name] = [_this_name] == 0 ? nameTimes[_this_name] + 1 : 0;
		
		var _this_value = null;
		if(Object.prototype.toString.call( data[_this_name]) === '[object Array]') {
			_this_value = data[_this_name][nameTimes[_this_name]];
		} else {
			_this_value = data[_this_name];       
		}
		if(_this.is("input")) {
			var _this_type = _this.attr("type")
			_this.val(_this_value);
			
		} else if(_this.is("select")) {
			_this.find("option[value=\""+ _this_value +"\"]").attr("selected", true);
		}
		
	});
	
}


/**
 * 重新登录
 */
function relogin(){
	window.parent.location.href="index.html";
}


/**
 * js获取项目根路径，如： http://localhost:8080/SerlfService
 * 
 * @returns
 */
function getRootPath() {
	var curWwwPath = window.document.location.href;
	var pathName = window.document.location.pathname;
	var pos = curWwwPath.indexOf(pathName);
	// 获取主机地址
	var localhostPaht = curWwwPath.substring(0, pos);
	// 获取带"/"的项目名，
	var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
	return (localhostPaht + projectName);
}

// 获取个人信息
function getUserInfo(id) {
    var obj = {
      mId:id
    };
    doPost("account/getMemberInfo.web", obj, function(data) {
        if (data.success) {
            window.userbean = data.reModel;
        } else {
            $.toast(data.errMsg,"text");
        }
    }, function(data) {
          $.toast(data.errMsg,"text");
    });
}